<template>
  <div>
    <el-page-header :icon="ArrowLeft" content="充值" />
    <el-button type="primary" @click="makePay()">点击充值</el-button>
    <el-dialog
      title="请用支付宝扫码支付"
      v-model="showQrcode"
      :width="deviceWidth"
    >
      <el-space direction="vertical" alignment="flex-start">
        <div>
          <el-alert
            v-if="showQrcode && !loading"
            :type="left_seconds > 30 ? 'success' : 'warning'"
            :closable="false"
            >剩余支付时间:{{ Math.floor(left_seconds / 60) }}分{{
              Math.round(left_seconds % 60)
            }}秒</el-alert
          >
        </div>
        <el-skeleton style="width: 240px" :loading="loading" animated>
          <template #template>
            <el-skeleton-item
              variant="image"
              style="width: 240px; height: 240px"
            />
          </template>
          <template #default>
            <el-card :body-style="{ padding: '0px', marginBottom: '1px' }">
              <QrcodeVue
                :value="qrcode_url"
                :size="200"
                level="H"
                v-if="showQrcode && !loading"
              />
            </el-card>
          </template>
        </el-skeleton>
      </el-space>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelPay()">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { useStore } from "vuex";
import { toRefs, ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ApiCreateOrder,
  ApiGetOrderStatus,
  ApiGetUserAccount,
} from "@/http/api";
import { generateOrderNo, isMobile } from "@/libs/utils.js";
import QrcodeVue from "qrcode.vue";
import {goTo} from "@/libs/utils"
export default {
  components: {
    QrcodeVue,
  },
  setup() {
    const store = useStore();
    const route = useRoute();
    const showQrcode = ref(false);
    const loading = ref(true);
    const qrcode_url = ref(null);
    const left_seconds = ref(null);
    let interval = null;
    let order_interval = null;
    const paid = ref(false);
    const deviceWidth = isMobile() ? "80%" : "30%";
    onMounted(() => {
      //挂载完成之后执行
      makePay();
    });
    const resetValue = () => {
      clearInterval(interval);
      clearInterval(order_interval);
      showQrcode.value = false;
      loading.value = true;
      qrcode_url.value = null;
      left_seconds.value = null;
      interval = null;
      order_interval = null;
      paid.value = false;
      //退出返回原路由
      goTo(route.query.redirect || "/");
    };
    function cancelPay() {
      resetValue();
      ElMessage.warning("取消支付!");
    }
    function makePay() {
      const order_no = generateOrderNo();
      ElMessageBox.prompt("请输入充值金额", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[1-9][0-9]{0,2}(\.\d{1,2})?$/,
        inputErrorMessage: "单次充值范围:￥1~￥999",
      })
        .then(({ value }) => {
          showQrcode.value = true;
          ApiCreateOrder({
            order_no,
            order_name: `桌面客户端充值￥${value}元`,
            order_amount: value,
          }).then((res) => {
            if (res.code === 2000) {
              loading.value = false;
              qrcode_url.value = res.data.qrcode;
              left_seconds.value = 600;
              interval = setInterval(() => {
                if (!paid.value && left_seconds.value > 1)
                  left_seconds.value -= 1;
                else {
                  ElMessage.error("超时未支付，订单关闭!");
                  resetValue();
                }
              }, 1000);
              order_interval = setInterval(() => {
                ApiGetOrderStatus({ order_no }).then((res) => {
                  if (res.code === 2000) {
                    if (res.data.paid) {
                      resetValue();
                      ElMessage.success("支付成功!");
                      ApiGetUserAccount().then((res) => {
                        if (res.code === 2000) {
                          store.commit("setUserAmount", res.data.amount);
                        } else {
                          ElMessage.error(res.message);
                        }
                      });
                    }
                  } else {
                    ElMessage.error(res.message);
                  }
                });
              }, 1000);
            } else {
              resetValue();
              ElMessage.error(res.message);
            }
          });
        })
        .catch(() => {
          resetValue();
          ElMessage.warning("取消充值");
        });
    }
    return {
      showQrcode,
      qrcode_url,
      loading,
      left_seconds,
      cancelPay,
      makePay,
      deviceWidth,
      ...toRefs(store.state),
    };
  },
};
</script>

<style lang="less" scoped>
</style>
